package com.boot.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.boot.controller.PushController;
import com.boot.entity.Ad;
import com.boot.entity.Manager;
import com.boot.entity.Push;
import com.boot.entity.User;
import com.boot.mapper.AdDao;
import com.boot.mapper.ManagerDao;
import com.boot.mapper.PushDao;
import com.boot.mapper.UserDao;
import com.boot.util.AdResult;
import com.boot.util.PushServerConfig;
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import org.json.JSONException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ManagerServiceImpl extends ServiceImpl<ManagerDao, Manager> implements com.boot.service.ManagerService {
	//超级管理员
	public static final char ADMIN_ROLE='1';
	//普通管理员
	public static final char NORMAL_ROLE='0';
	@Resource
	private ManagerDao managerDao;
	@Resource
	private AdDao adDao;
	@Resource
	private PushDao pushDao;
	@Resource
	private UserDao userDao;
	
	@Override
	public AdResult getMyAreaNeedCheckAd(String acount) {
		AdResult adResult=new AdResult();
		List<Ad> ads=managerDao.getMyAreaNeedCheckAd(acount);
		if(ads.size()>0){
			adResult.setData(ads);
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("未获取到数据");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult getNeedCheckAd() {
		AdResult adResult=new AdResult();
		List<Ad> ads=managerDao.getNeedCheckAd();
		if(ads.size()>0){
			System.out.println("dssd");
			adResult.setData(ads);
			adResult.setMsg("获取成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("未获取到数据");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult getManagerInfo(Manager manager) {
		AdResult adResult=new AdResult();
		Manager managerresult = managerDao.getManagerInfoByAcount(manager);
		if(managerresult!=null){
			if(managerresult.getPassword().equals(manager.getPassword())){
				adResult.setData(managerresult);
				adResult.setMsg("获取到了管理者");
				adResult.setStatus(1);
			}else{
				adResult.setMsg("密码错误");
				adResult.setStatus(2);
			}
		}else{
			adResult.setMsg("账号不存在");
			adResult.setStatus(0);
		}
		return adResult;
	}

	@Override
	public AdResult adIsOk(String ad_id,Integer ispush) {
		AdResult adResult=new AdResult();
		int result=managerDao.updateAdStatusOk(ad_id);
		System.out.println("修改结果："+result);
		if(result>0){
			adResult.setMsg("审核通过");
			adResult.setStatus(1);
			if(ispush==1){
				//获取当前推送广告的详情
				Ad ad=adDao.getAdById(ad_id);
				System.out.println("ad:"+ad);
				//是推送广告调用推送接口
				HashMap<String, String> map=new HashMap<String, String>();
				map.put("ad_id", ad.getAd_id());
				if(ad.getTitle()!=null){
					map.put("title", ad.getTitle());
				}
				if(ad.getContent()!=null){
					map.put("content", ad.getContent());
				}
				//根据发布设置的参数筛选用户拼接成“...&...&...”格式
				String usernamesAn="";//安卓用户参数
				String usernamesIos="";//ios用户
				List<Push> pushes=managerDao.getPushesByAdId(ad_id);
				List<Push> pushAn=new ArrayList<>();
				List<Push> pushIos=new ArrayList<>();
				for(int i=0;i<pushes.size();i++){
					if(pushes.get(i).getDevicetype().equals("a")){
						pushAn.add(pushes.get(i));
					}
					if(pushes.get(i).getDevicetype().equals("i")){
						pushIos.add(pushes.get(i));
					}
				}
				for(int i=0;i<pushAn.size();i++){
					System.out.println("username:"+pushAn.get(i).getUsername());
					if(i==pushAn.size()-1){
						usernamesAn+=pushAn.get(i).getUsername();
					}else{
						usernamesAn+=pushAn.get(i).getUsername();
						usernamesAn+=",";
					}
				}
				for(int i=0;i<pushIos.size();i++){
					if(i==pushIos.size()-1){
						usernamesIos+=pushIos.get(i).getUsername();
					}else{
						usernamesIos+=pushIos.get(i).getUsername();
						usernamesIos+=",";
					}
				}
				map.put("usernames", usernamesAn);
				System.out.println(map);
		    	Map<String, String> urlmap = new HashMap<String, String>();
		    	urlmap.put("action", "send");
				System.out.println(PushServerConfig.pushServerInterFace);
				//PushController.sendPost(PushServerConfig.pushServerIp+"notification.do?", urlmap, map);
				//本机向安卓用户推送时调用此方法
			    PushController.sendPost(PushServerConfig.pushServerInterFace, urlmap, map);
			    //向苹果用户推送时调用次方法
			    if(!usernamesIos.equals("")){
			    	map.put("usernameios", usernamesIos);
				    pushToIosUsers(map);
			    }
			}
		}else{
			adResult.setMsg("修改失败");
			adResult.setStatus(0);
		}
		return adResult;
	}

	/**
	 * 向苹果用户推送
	 * 需要推送的广告信息和所有符和条件的ios用户都存放在map对象中
	 * @param map
	 */
	private void pushToIosUsers(HashMap<String, String> map) {
		  
		  System.out.println("zsl==========开始推送消息");
          int badge = 1; // 图标小红圈的数值
          String sound = "default"; // 铃音
          String msgCertificatePassword = "xgg+20180524";//导出证书时设置的密码
          String deviceToken = map.get("usernameios"); //手机设备token号
          //String message = "test push message to ios device";
          String message=map.get("title");
          String body=map.get("content");
          List<String> tokens = new ArrayList<String>();
          String[] tokenstrs=deviceToken.split(",");
          for(int i=0;i<tokenstrs.length;i++){
        	  tokens.add(tokenstrs[i]);
          }
//        String certificatePath = requestRealPath
//                + "/WEB-INF/classes/certificate/msg.p12";
          //java必须要用导出p12文件  php的话是pem文件
          //String certificatePath = "G:"+File.separator+"xggsource"+File.separator+"zhengshu"+File.separator+"aps.p12";
          //String certificatePath="/root/anps/aps.p12";
          String certificatePath=PushServerConfig.certificatePath;
          boolean sendCount = true;
//          if(tokenstrs.length>1){
//        	  sendCount=false;
//          }
          PushNotificationPayload payload = new PushNotificationPayload();
          try {
			payload.addAlert(message);
			payload.addSound(sound);
			payload.addCustomDictionary("ad_id", map.get("ad_id"));
	          PushNotificationManager pushManager = new PushNotificationManager();
	          // true：表示的是产品测试推送服务 false：表示的是产品发布推送服务
	          pushManager.initializeConnection(new AppleNotificationServerBasicImpl(
	                  certificatePath, msgCertificatePassword, false));
	          List<PushedNotification> notifications = new ArrayList<PushedNotification>();
	          // 开始推送消息
	          if (sendCount) {
	        	  PushedNotification notification=null;
	        	  for(int i=0;i<tokens.size();i++){
	        		  Device device = new BasicDevice();
	        		  //动态设置
	        		  User user=userDao.getUnReadedAds(tokens.get(i));
	      			  payload.addBadge(user.getUnReadedAds());
	      			  
		              device.setToken(tokens.get(i));
		              notification = pushManager.sendNotification(device, payload, true);
	        	  }
	              notifications.add(notification);
	          } else {
	              List<Device> devices = new ArrayList<Device>();
	              System.out.println(tokens);
	              BasicDevice basicDevice=null;
	              for (String token : tokens) {
	            	  basicDevice=new BasicDevice(token);
	                  devices.add(basicDevice);
	              }
	              notifications = pushManager.sendNotifications(payload, devices);
	          }
	          List<PushedNotification> failedNotification = PushedNotification
	                  .findFailedNotifications(notifications);
	          List<PushedNotification> successfulNotification = PushedNotification
	                  .findSuccessfulNotifications(notifications);
	          int failed = failedNotification.size();
	          int successful = successfulNotification.size();
	          System.out.println("zsl==========成功数：" + successful);
	          System.out.println("zsl==========失败数：" + failed);
	          pushManager.stopConnection();
	          System.out.println("zsl==========消息推送完毕");
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (CommunicationException e) {
			e.printStackTrace();
		} catch (KeystoreException e) {
			e.printStackTrace();
		} catch (InvalidDeviceTokenFormatException e) {
			e.printStackTrace();
		}
	}

	@Override
	public AdResult adIsBad(String ad_id) {
		AdResult adResult=new AdResult();
		int result=managerDao.updateAdStatusBad(ad_id);
		if(result>0){
			adResult.setMsg("修改成功");
			adResult.setStatus(1);
		}else{
			adResult.setMsg("修改失败");
			adResult.setStatus(0);
		}
		return adResult;
	}
	
//	public static void main(String[] args) {
//		Properties properties=new Properties();
//    	try {
////    		InputStream in = ManagerServiceImpl.class.getResourceAsStream("config.properties");
////    		properties.load(in);
//			properties.load(new FileInputStream("config.properties"));
//			String pushServerIp=properties.getProperty("pushServerIp");
//			System.out.println(pushServerIp);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

}
